﻿#coding: utf-8

require 'dm-validations'
require 'json'
require 'set'

class Node
	include DataMapper::Resource

	property :id, Serial
	property :title, Text

	belongs_to :thematic

	has n, :content
	has n, :links, :child_key => [:source_id]
	has n, :node, self, :through => :links, :via => :target

	def to_json(*a)
		{
			'id' => id.to_i,
			'title' => title.to_s,
			'thematic' => Thematic.first(:id => thematic_id).label
		}.to_json(*a)
	end

	def to_json_with_contents(*a)
		{
			'id' => id.to_i,
			'title' => title.to_s,
			'thematic' => Thematic.first(:id => thematic_id).label,
			'contents' => findRelatedContents
		}.to_json(*a)
	end

	def findRelatedContents
		rc = []
		Content.all(:node_id => id).each{|c| rc << c unless c.nil?}
		rc
	end
	
	def findLinkedNodes
		rc = Set.new
		result = Link.all(:source_id => id) | Link.all(:target_id => id)
		result.each {|n| rc << n unless n.nil?}
		rc.to_a
	end
end
